import axios from 'axios'
// import qs from 'qs'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'
let onceError = false // 关闭token失效连续报错

axios.defaults.timeout = 300000

// request interceptor
axios.interceptors.request.use(
  config => {
    // do something before request is sent

    if (store.getters.token) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      config.headers['X-Access-Token'] = getToken()
    }
    // if (config.method === 'post') {
    //   config.url = config.url + "?_t" + Date.parse(new Date()) / 1000
    //   if(config.data instanceof FormData){
    //     config.data.append("_t",Date.parse(new Date()) / 1000)
    //    }else{
    //     config.data._t= Date.parse(new Date()) / 1000
    //    }
    // } else if (config.method === 'get') {
    //   config.params = {
    //     _t: Date.parse(new Date()) / 1000,
    //     ...config.params
    //   }
    // }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
axios.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
  */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    // const res = response.data
    // if the custom code is not 20000, it is judged as an error.
    if (response.data.code && response.data.code !== 200) {
      if (response.data.code === 401) {
        if (onceError) return response
        else onceError = true
        // to re-login
        Message({
          message: '身份信息失效，请重新登录',
          type: 'error',
          duration: 3 * 1000
        })
        store.dispatch('user/resetToken').then(() => {
          location.reload()
        })
        // MessageBox.confirm('身份信息失效，请重新登录', '提示', {
        //   confirmButtonText: '去登录',
        //   showClose: false,
        //   showCancelButton: false,
        //   closeOnClickModal: false,
        //   closeOnPressEscape: false,
        //   closeOnHashChange: false,
        //   type: 'warning'
        // }).then(() => {
        //   store.dispatch('user/resetToken').then(() => {
        //     location.reload()
        //   })
        // })
      } else {
        onceError = false
        Message({
          message: response.data.message || 'Error',
          type: 'error',
          duration: 5 * 1000
        })
      }
      return Promise.reject(new Error(response.data.message || 'Error'))
    } else {
      onceError = false
      return response
    }
  },
  error => {
    console.log('err' + error) // for debug
    Message({
      message: error.message ? error.message : '请求超时',
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export function get(url, params, header, forResponse) {
  return new Promise((resolve, reject) => {
    axios.get(process.env.VUE_APP_BASE_API + url, Object.assign({
      params: params
    }, header || {})
    ).then(res => {
      if (forResponse) resolve(res)
      resolve(res.data)
    }).catch(err => {
      reject(err)
    })
  })
}

export function post(url, params, header, forResponse) {
  return new Promise((resolve, reject) => {
    axios.post(process.env.VUE_APP_BASE_API + url, Object.assign(params || {}, header || {})
    ).then(res => {
      if (forResponse) resolve(res)
      resolve(res.data)
    }).catch(err => {
      reject(err)
    })
  })
}

export function put(url, params) {
  return new Promise((resolve, reject) => {
    axios.put(process.env.VUE_APP_BASE_API + url, params)
      .then(res => {
        resolve(res.data)
      }).catch(err => {
        reject(err)
      })
  })
}
export function del(url, params) {
  return new Promise((resolve, reject) => {
    console.log('---------->' + params.toString(), params.id)
    axios.delete(process.env.VUE_APP_BASE_API + url, params)
      .then(res => {
        resolve(res.data)
      }).catch(err => {
        reject(err)
      })
  })
}
